package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.web.page.PageDomain;
import com.ruoyi.common.core.web.page.TableDataInfo;
import com.ruoyi.common.core.web.page.TableSupport;
import com.ruoyi.system.domain.SysDept;
import com.ruoyi.system.domain.TbHouseInfo;
import com.ruoyi.system.domain.TbPremisesInfo;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ITbHouseInfoService;
import com.ruoyi.system.service.ITbPremisesInfoService;
import org.assertj.core.util.Lists;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.PreAuthorize;
import com.ruoyi.system.domain.TbRoomInfo;
import com.ruoyi.system.service.ITbRoomInfoService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;

/**
 * 房源信息Controller
 * 
 * @author ruoyi
 * @date 2021-06-19
 */
@RestController
@RequestMapping("/xinxi")
public class TbRoomInfoController extends BaseController
{
    @Autowired
    private ITbRoomInfoService tbRoomInfoService;
    @Autowired
    private ITbHouseInfoService houseInfoService;
    @Autowired
    private ITbPremisesInfoService premisesInfoService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @PreAuthorize(hasPermi = "resource:xinxi:selHousing")
    @GetMapping("selHousing")
    public List<TbRoomInfo> selHousing(Integer id) throws IOException {
//        ArrayList<TbRoomInfo> list = new ArrayList<>();

        List<TbRoomInfo> list=tbRoomInfoService.selHousing(id);
        return list;

    }

    /**
     * 添加房源信息
     * @param tbRoomInfo
     * @return
     */
    @PreAuthorize(hasPermi = "resource:xinxi:addroominfo")
    @PostMapping("addroominfo")
    @Transactional
    public boolean addroominfo(@RequestBody TbRoomInfo tbRoomInfo){
        System.out.println(tbRoomInfo);
        boolean aa=false;
        //添加house_info
        TbHouseInfo tbHouseInfo = new TbHouseInfo();
        tbHouseInfo.setPremisesId(tbRoomInfo.getLouid());
        //雪花算法id
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        long l = snowflake.nextId();
        tbHouseInfo.setId(String.valueOf(l));
        tbHouseInfo.setStatus(tbRoomInfo.getSt());
        tbHouseInfo.setCreateBy(String.valueOf(tbRoomInfo.getLouid()));
        aa=houseInfoService.addfang(tbHouseInfo);
        if(aa){
            //添加room_info
            Snowflake snowflakes = IdUtil.createSnowflake(1, 1);
            long ls = snowflake.nextId();
            tbRoomInfo.setId(String.valueOf(ls));
            tbRoomInfo.setHouseId(tbHouseInfo.getId());
            aa=tbRoomInfoService.addroominfo(tbRoomInfo);
            //如果数据全部添加成功，将数据添加到es
            if(aa){
                //首先将数据发送至mq，通过mq进行操作
                System.out.println("将要发送mq的值====="+tbRoomInfo);
                rabbitTemplate.convertAndSend("topicExchange","*.first",JSON.toJSONString(tbRoomInfo));
            }
        }

        return aa;
    }


    /**
     * 查询房源信息列表
     * @return
     */
    @PreAuthorize(hasPermi = "resource:xinxi:list")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody TbRoomInfo tbRoomInfo) throws IOException {
        startPage();

        //获取es
        GetIndexRequest re = new GetIndexRequest("roominfo");
        //判断有没有es库
        boolean exists = restHighLevelClient.indices().exists(re, RequestOptions.DEFAULT);
        //判断es库是否存在
        if(exists){
            System.out.println(tbRoomInfo.getRoomName());
            //获取es库数据请求
            SearchRequest roomInfo1 = new SearchRequest("roominfo");

            //查询条件
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
            //查询条件
            if(tbRoomInfo.getRoomName()==null || tbRoomInfo.getRoomName().equals("")){
                searchSourceBuilder.query(QueryBuilders.matchAllQuery());
            }else{
                searchSourceBuilder.query(QueryBuilders.multiMatchQuery(tbRoomInfo.getRoomName(),"room_name"));
                //高亮请求
                HighlightBuilder highlightBuilder = new HighlightBuilder();
                highlightBuilder.field("room_name");
                highlightBuilder.preTags("<span style=\"color: red\">");
                highlightBuilder.postTags("</span>");
                searchSourceBuilder.highlighter(highlightBuilder);
            }
            //分页
            searchSourceBuilder.from(tbRoomInfo.getPageNum()*tbRoomInfo.getPageSize());
            searchSourceBuilder.size(tbRoomInfo.getPageSize());
            //将查询条件放入请求
            roomInfo1.source(searchSourceBuilder);
            //发送请求
            SearchResponse search = restHighLevelClient.search(roomInfo1, RequestOptions.DEFAULT);
            //获取条数
            int total = (int) search.getHits().getTotalHits().value;
            SearchHit[] hits = search.getHits().getHits();
            //返回的list集合
            List<Map<String,Object>> list = Lists.newArrayList();
            for (SearchHit hit : hits) {
                //高亮结果
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                HighlightField room_name = highlightFields.get("room_name");
                //原来的结果
                Map<String, Object> sourceAsMap = hit.getSourceAsMap();
                //解析高亮
                //判断字段是否为空
                if(room_name!=null){
                    //获取值
                    Text[] fragments = room_name.fragments();
                    //空字符串
                    String ntitle="";
                    //循环值
                    for (Text fragment : fragments) {
                        //循环添加
                        ntitle+=fragment;
                    }
                    sourceAsMap.put("room_name",ntitle);

                }
                sourceAsMap.put("total",total);
                list.add(sourceAsMap);
            }
            return getDataTable(list);
        }else {
            System.out.println("在数据库获取");
            //获取值
            List<TbRoomInfo> list = tbRoomInfoService.selectList();
            System.out.println(list);

            //创建es
            CreateIndexRequest request = new CreateIndexRequest("roominfo");
            //发送创建请求
            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            System.out.println("创建es成功");
            //向es添加数据(bulk)
//            BulkRequest bulk = new BulkRequest();
//            for (int i = 0; i < list.size(); i++) {
//                System.out.println(i);
//                bulk.add(new IndexRequest("roominfo")
//                        .source(JSON.toJSONString(list.get(i)),XContentType.JSON));
//            }
//            BulkResponse bulk1 = restHighLevelClient.bulk(bulk, RequestOptions.DEFAULT);
            //循环添加数据
            for (TbRoomInfo roomInfo : list) {
                //创建添加
                IndexRequest roominfo = new IndexRequest("roominfo");
                //添加
                IndexRequest source = roominfo.source(JSON.toJSONString(roomInfo), XContentType.JSON);
                source.id(roomInfo.getId());
                //发送请求
                restHighLevelClient.index(roominfo,RequestOptions.DEFAULT);
            }
            System.out.println("添加成功");
            return getDataTable(list);
        }
    }

    /**
     * 导出房源信息列表
     */
    @PreAuthorize(hasPermi = "resource:xinxi:export")
    @Log(title = "房源信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TbRoomInfo tbRoomInfo) throws IOException
    {
        List<TbRoomInfo> list = tbRoomInfoService.selectTbRoomInfoList(tbRoomInfo);
        ExcelUtil<TbRoomInfo> util = new ExcelUtil<TbRoomInfo>(TbRoomInfo.class);
        util.exportExcel(response, list, "房源信息数据");
    }

    /**
     * 获取房源信息详细信息
     */
    @PreAuthorize(hasPermi = "resource:xinxi:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(tbRoomInfoService.selectTbRoomInfoById(id));
    }

    /**
     * 新增房源信息
     */
    @PreAuthorize(hasPermi = "resource:xinxi:add")
    @Log(title = "房源信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TbRoomInfo tbRoomInfo)
    {
        return toAjax(tbRoomInfoService.insertTbRoomInfo(tbRoomInfo));
    }

    /**
     * 修改房源信息
     */
    @PreAuthorize(hasPermi = "resource:xinxi:edit")
    @Log(title = "房源信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TbRoomInfo tbRoomInfo)
    {
        return toAjax(tbRoomInfoService.updateTbRoomInfo(tbRoomInfo));
    }

    /**
     * 删除房源信息
     */
    @PreAuthorize(hasPermi = "resource:xinxi:remove")
    @Log(title = "房源信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tbRoomInfoService.deleteTbRoomInfoByIds(ids));
    }
}
